package com.fc.v2.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

public class ImageUtil {
    public static String upload(MultipartFile file, String path) {
        // 获取当前项目所在磁盘绝对路径
        String projectPath = null;
        try {
            projectPath = new File("").getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 定义图片上传路径
        String basePath = projectPath + path;
        // 判断upload文件夹是否存在
        File uploaded = new File(basePath);
        if (!uploaded.exists()) {
            uploaded.mkdir();
        }
        // 获得上传文件的名称
        String fileName = file.getOriginalFilename();
        // 使用UUID改写fileName确保图片在服务器的唯一性
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 将生成的uuid和fileName进行拼接
        String newFileName = uuid + "-" + fileName;
        // 创建一个文件实例对象
        File img = new File(basePath, newFileName);
        // 对这个文件进行上传的操作
        try {
            file.transferTo(img);
        } catch (IOException e) {
            return null;
        }
        return newFileName;
    }

    public static void download(String fileUrl) {
        // 获取当前项目所在磁盘绝对路径
        String projectPath = null;
        try {
            projectPath = new File("").getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置发送到客户端的响应内容类型
        HttpServletResponse response = ServletUtils.getResponse();
        ServletUtils.getResponse().setContentType("image/*");
        //读取本地图片输入流
        try {
            FileInputStream inputStream = new FileInputStream(projectPath + fileUrl);
            OutputStream out = response.getOutputStream();
            int i = inputStream.available();
            //byte数组用于存放图片字节数据
            byte[] buff = new byte[i];
            inputStream.read(buff);
            out.write(buff);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
